const pathToRegexp = require("path-to-regexp");

function Layer(path, handler) {
  this.path = path;
  this.handler = handler;
  // 把路径转成正则
  this.reg = pathToRegexp(this.path, (this.keys = []));
  // console.log(this.reg, this.keys);
}

Layer.prototype.match = function (path) {
  let match = path.match(this.reg);
  /* 
  console.log(match, "match");
  [
    '/user/1/2',
    '1',
    '2',
    index: 0,
    input: '/user/1/2',
    groups: undefined
    ]
   */
  if (match) {
    // layer.params = this.keys;
    this.params = this.keys.reduce((memo, current, index) => {
      memo[current.name] = match[index + 1];
      return memo;
    }, {});
    return true;
  }
  if (this.path === path) {
    return true;
  }
  if (!this.route) {
    // 是中间件, 进行特殊处理
    if (this.path === "/") {
      return true;
    }
    return path.startsWith(this.path + "/");
  }
  return false;
};

Layer.prototype.handle_request = function (req, res, next) {
  this.handler(req, res, next);
};
Layer.prototype.handle_error = function (err, req, res, next) {
  if (this.handler.length === 4) {
    // 如果参数个数是4个，说明找到错误处理中间件
    return this.handler(err, req, res, next);
  } else {
    // 继续向下传递
    next(err);
  }
};
module.exports = Layer;
